/**
 * @Title: table-form-student.js
 * @Description: table-form-student
 * @author: Fanchao
 * @date: 2020/9/15 9:30 上午
 * @version V1.0
 */
import React, { useState } from "react";
import { Button, Form, Input, message, Modal, Radio, Table } from "antd";

const layout = {
    labelCol: { span: 3 },
    wrapperCol: { span: 21 },
};
const TableFormStudent = ({ evaluateExamItemId, questionSnapshotsModelList, evaluatePlanSnapshotsModel: { planSnapshotsDetailModels }, initExamItemAnswerDetailMsgList, evaluateTaskType, showBtn, dispatch, history }) => {
    const [form] = Form.useForm();

    const [visible, setVisible] = useState(false);
    const createNewArr = (data) => {
        return data.reduce((result, item) => {
            //首先将name字段作为新数组result取出
            if (result.indexOf(item.category) < 0) {
                result.push(item.category);
            }
            return result;
        }, []).reduce((result, category) => {
            //将name相同的数据作为新数组取出，并在其内部添加新字段**rowSpan**
            const children = data.filter(item => item.category === category);
            result = result.concat(
                children.map((item, index) => ({
                    ...item,
                    //将第一行数据添加rowSpan字段
                    rowSpan: index === 0 ? children.length : 0,
                })),
            );
            return result;
        }, []);
    };
    const columns = [
        // {
        //     title: '序号',
        //     align: 'left',
        //     render: (text, row, index) => {
        //         return {
        //             children: index + 1,
        //             props: {
        //                 rowSpan: row.rowSpan,
        //             },
        //         };
        //     },
        // },
        // {
        //     title: '评价指标',
        //     dataIndex: 'category',
        //     key: 'category',
        //     align: 'left',
        //     render: (text, row, index) => {
        //         return {
        //             children: row.category,
        //             props: {
        //                 rowSpan: row.rowSpan,
        //             },
        //         };
        //     },
        // },
        {
            title: '评价标准',
            dataIndex: 'checkPoint',
            key: 'checkPoint',
            align: 'left',
        },
        // {
        //     title: '权重',
        //     dataIndex: 'weight',
        //     key: 'weight',
        //     align: 'left',
        // },
    ];
    for (let i = 0; i < planSnapshotsDetailModels.length; i++) {
        columns.push({
            title: () => {
                return (
                    <>
                        <div>{planSnapshotsDetailModels[i].optionContent}</div>
                        {/*<div>{planSnapshotsDetailModels[i].score}</div>*/}
                    </>
                );
            },
            align: 'left',
            render: (text, row, index) => {
                return (
                    <Radio
                        value={initExamItemAnswerDetailMsgList[index].planSnapshotsDetailId}
                        checked={initExamItemAnswerDetailMsgList[index].planSnapshotsDetailId === planSnapshotsDetailModels[i].planSnapshotsDetailId}
                        onChange={(e) => onChange(e, planSnapshotsDetailModels[i].planSnapshotsDetailId, index)}
                    />
                );
            },
        });
    }
    const onChange = (e, planSnapshotsDetailId, index) => {
        if (!showBtn) {
            message.success('您的任务已完成，请勿重复评价！');
            return;
        }
        const newInitExamItemAnswerDetailMsgList = initExamItemAnswerDetailMsgList;
        newInitExamItemAnswerDetailMsgList[index].planSnapshotsDetailId = planSnapshotsDetailId;
        dispatch({
            type: 'myTaskDetail/setInitExamItemAnswerDetailMsgList',
            payload: newInitExamItemAnswerDetailMsgList,
        });
    };
    const submitBtn = () => {
        // 是否都勾选
        const isAllComplete = initExamItemAnswerDetailMsgList.some(item => {
            return item.planSnapshotsDetailId === '';
        });
        if (isAllComplete) {
            message.warn('打分项需要全部勾选');
            return;
        }
        // 学生是否全部选择第一项
        const studentAllOk = initExamItemAnswerDetailMsgList.every(item => {
            return item.planSnapshotsDetailId === planSnapshotsDetailModels[0].planSnapshotsDetailId;
        });
        // 教师是否全部选择第一或者最后一项
        const expertAllOkOrAllFail = initExamItemAnswerDetailMsgList.every(item => {
            return item.planSnapshotsDetailId === planSnapshotsDetailModels[0].planSnapshotsDetailId || item.planSnapshotsDetailId === planSnapshotsDetailModels.slice(-1)[0].planSnapshotsDetailId;
        });

        // 学生教员试卷的分情况提交
        if (evaluateTaskType === 'student') {
            if (studentAllOk) {
                message.warn(`不能全部选择${planSnapshotsDetailModels[0].optionContent}`);
                return;
            }
            submitFetch('');
        } else if (evaluateTaskType === 'expert') {
            if (expertAllOkOrAllFail) {
                setVisible(true);
            } else {
                submitFetch('');
            }
        }else {
            //其他类型直接提交
            submitFetch('');
        }
    };
    const submitFetch = (comment) => {
        const params = {
            evaluateExamItemId,
            examItemAnswerDetailMsgList: initExamItemAnswerDetailMsgList,
            comment,
        };
        dispatch({
            type: 'myTaskDetail/submitFetch',
            payload: params,
            callback: (result) => {
                if (result) {
                    setVisible(false);
                    history.push('/my-tasks');
                }
            },
        });
    };
    return (
        <>
            <Table
                bordered={true} // 是否有边框
                columns={columns}
                rowKey='evaluateQuestionSnapshotsId'
                dataSource={createNewArr(questionSnapshotsModelList)}
                pagination={false}
            />
            {
                showBtn ? (<div style={{ marginTop: '16px', textAlign: 'right' }}>
                    <Button type="primary" onClick={submitBtn}>提交</Button>
                </div>) : null
            }
            <Modal
                title="填写备注"
                visible={visible}
                onOk={() => {
                    form.validateFields().then(values => {
                        submitFetch(values.comment);
                    }).catch(info => {
                    });
                }}
                onCancel={() => {
                    setVisible(false);
                    form.resetFields();
                }}
            >
                <Form
                    {...layout}
                    layout="horizontal"
                    form={form}
                    name="basic"
                    initialValues={{}}
                >
                    <Form.Item
                        label="备注"
                        name="comment"
                        rules={[
                            { required: true, message: '必填' },
                            { min: 200, message: '少于200字' },
                        ]}
                    >
                        <Input.TextArea
                            autoSize={{ minRows: 2, maxRows: 6 }}
                            placeholder="您的打分评价全部为最高分，需要填写详情备注，最少200字，请填写！"
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default TableFormStudent;
